package cn.circle.system.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import cn.circle.commom.controller.BackendBaseController;
import cn.circle.commom.dao.impl.BaseDaoImpl;
import cn.circle.system.model.SysCustomer;
import cn.circle.system.model.SysMenus;
import cn.circle.system.model.SysRoles;
import cn.circle.system.pagemodel.LoginInfo;
import cn.circle.system.pagemodel.TreeNode;
import cn.circle.system.service.ISystemService;
import cn.circle.system.util.MD5;
import cn.circle.system.util.RemoteHost;
import cn.circle.system.util.ReturnInfo;
import cn.circle.system.util.TreeUtil;



@Controller
@EnableWebMvc
@SuppressWarnings("unchecked")
public class SystemController extends BaseDaoImpl{

	@Autowired
	private ISystemService systemService;
	
	/**
	 * 跳转到登录页面
	 */
	@RequestMapping(value = "/manage/goLogin")
	public String goLogin() {
		return "/WEB-INF/pages/login.jsp";
	}
	/**
	 * 响应用户登录请求
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/manage/doLogin")
	public ReturnInfo doLogin(String userName,String userPwd, ReturnInfo info, HttpServletRequest request) throws Exception {

		/*String username;
		String introduction;
		userPwd = MD5.md5(userPwd);
		username = new String(userName.getBytes("iso8859-1"),"utf-8");
		introduction = new String(userPwd.getBytes("iso8859-1"),"utf-8");
		System.out.println(userName);
		System.out.println(userPwd);
		System.out.println(username);
		if (systemService.login(username,introduction)) {
			//将登录用户信息存入session
			HttpSession session = request.getSession();
			session.setAttribute("user", username);
			info.setSuccess(0);
		} else {
			info.setSuccess(1);
			info.setMsg("用户名和密码不能为空!");
		}
		return info;*/

		if (userName != null && userPwd != null) {
			userPwd = MD5.md5(userPwd); // MD5加密登录密码
			
			String hql = " from SysCustomer t where t.userName ='" + userName + "' ";
			Query query = super.sessionFactory.getCurrentSession().createQuery(hql);
			
			List<SysCustomer> lst = query.list();
			System.out.println(lst);
			if (lst != null && lst.size() == 1) {
				
				SysCustomer current = lst.get(0);
				// 只需要第一条
				if (userPwd.equals(current.getPassWord())) {
					if (current.getStatus() == 9) {
						LoginInfo loginInfo;
						// 构造session
						if(current.getSysDepartment() == null){
							loginInfo = new LoginInfo(current.getCustId(),null,current.getSysRoles().getRoleName(), null, current.getSysRoles().getId(),
									current.getUserName(), current.getPhoto(),RemoteHost.getRemoteHost(this.getRequest()),current.getLastLoginTime(),current.getPhone(),
									null, System.currentTimeMillis());
						}
						else{
							
							loginInfo = new LoginInfo(current.getCustId(), current.getSysDepartment().getDepName(),current.getSysRoles().getRoleName(),current.getSysDepartment().getDepId(), current.getSysRoles().getId(),
									current.getUserName(), current.getPhoto(), RemoteHost.getRemoteHost(this.getRequest()),current.getLastLoginTime(),current.getPhone(),
									null, System.currentTimeMillis());
						}
						//获取该用户可操作的菜单
						if(null != current.getSysRoles().getId() && !"".equals(current.getSysRoles().getId()))
						{
							Map<String,String> mapIds = new HashMap<String,String>();
							hql = " from SysRoles t where t.id in (" + current.getSysRoles().getId() + ") ";
							query = super.sessionFactory.getCurrentSession().createQuery(hql);
							
							List<SysRoles> lstMenuIds = query.list();
							
							Iterator<SysRoles> it = lstMenuIds.iterator();
							while(it.hasNext())
							{
								SysRoles rd = it.next();
								String menus = rd.getRoleMenus();
								System.out.print(menus);
								if(StringUtils.isNotEmpty(menus))
								{
									String[] menuIds = menus.split(",");
									for(int i=0;i<menuIds.length;i++)
									{
										String id = menuIds[i].trim();
										if(StringUtils.isNotEmpty(id))
										{
											mapIds.put(id, "");
										}
									}
								}
							}
							
							Set<String> idsSet = mapIds.keySet();
							loginInfo.setModuleIds(idsSet);
							System.out.print(loginInfo);
							
						}
						//将登录用户信息存入session
						HttpSession session = request.getSession();
						session.setAttribute("user", loginInfo);

						// 更新用户信息
						hql = "update SysCustomer s set s.lastLoginTime = now(),s.loginIp = '"
								+ RemoteHost.getRemoteHost(this.getRequest()) + "' where s.custId in ("
								+ current.getCustId() + ") ";
						query = super.sessionFactory.getCurrentSession().createQuery(hql);
						query.executeUpdate();

					} else {
						info.setSuccess(1);
						info.setMsg("用户状态异常,不能登录,请联系管理员!");
					}
				}
				else{
					info.setSuccess(1);
					info.setMsg("用户名或密码错误!");
				}
				
			} else {
				info.setSuccess(1);
				info.setMsg("用户名或密码错误!");
			}
		} else {
			info.setSuccess(1);
			info.setMsg("用户名和密码不能为空!");
		}
		return info;
	}
	
	/**
	 * 功能说明：获取当前登录用户可操作的功能菜单信息，通过用户的角色编号来获取
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "/manage/showMenu")
	public ReturnInfo showMenu(HttpServletRequest request,ReturnInfo info){
		HttpSession session = request.getSession();
		if(session.getAttribute("user") !=null && session.getAttribute("user") != ""){
			info.setRows(fetchMenu(BackendBaseController.getUserMoudleIds(request)));
		}else{
			info.setSuccess(1);
			info.setMsg("请先登录系统！");
		}
		return info;
	}	
	private List<TreeNode> fetchMenu(String moduleIds){
		List<TreeNode> lstTree = null;
		if(StringUtils.isNotEmpty(moduleIds))
		{
			String hql = " from SysMenus t where t.status = 9 and t.id in (" +moduleIds + ") order by showOrder  "; 
			List<SysMenus> lstAll = super.find(hql);
			
			if(lstAll!=null && lstAll.isEmpty()==false){
				TreeUtil treeUtil = new TreeUtil();
				treeUtil.setLstAll(lstAll);
				lstTree = treeUtil.findById(null);	
			}
		}
		return lstTree;
	}

}
